import React, { Component } from 'react';
import { connect } from 'react-redux';
import { requestCreateUser, getRegPoint } from '../../../store/actions';
import 'flex.css/dist/data-flex.css';
import Input from 'components/form/input'
import Button from 'components/button/button'
import Checkbox from 'components/form/checkbox'
import Uploader from 'components/form/uploader'
import Toptip from 'components/toptip/toptip'
import { Toast } from 'antd-mobile'
import { validForm, validValue } from 'Utils/lite-validator.js'
import utils from 'Utils'


@connect(
  state=>state
)
export default class Register extends React.Component {
  constructor () {
    super()
    this.state = {
      errMsg: '',
      errShow:false,
      errTimmer:null,
      disabled: true,
      inCodeReadonly: false,
      wxUploadRes:[],
      formData:{
        address:'',
        company:'',
        invitationCode:'',
        name:'',
        phone:'',
        read:'',
      }
    }
    this.updateState = this.updateState.bind(this);
    this.uploadImgSucccess = this.uploadImgSucccess.bind(this);
    this.uploadImgDelete = this.uploadImgDelete.bind(this);
    this.uploadImgClick = this.uploadImgClick.bind(this);
  }
  updateState(stateName){
    return e => {
      let v;
      if(stateName === 'read'){
        v = e.target.checked;
        this.setState({disabled: !v });
      }else{
        v = e.target.value;
      }
      this.setState({
        'formData':{
          ...this.state.formData,
          [stateName]:v
        }
      })
    }
  }
  componentDidMount(){
    this.props.dispatch(getRegPoint({type:this.props.location.query.type}));
    var inCode = utils.getUrlParam('inCode');
    var formData = this.state.formData;
    console.log('inCode')
    console.log(inCode)
    if(inCode){
      formData.invitationCode = inCode;
      this.setState({
        inCodeReadonly:true,
        formData:formData
      })
    }
  }
  componentWillUnmount(){
    this.state.errTimmer && clearTimeout(this.state.errTimmer);
  }
  showWran(msg){
    this.state.errTimmer && clearTimeout(this.state.errTimmer);
    this.setState({
      errShow: true,
      errMsg: msg,
      errTimmer: setTimeout(()=>{
        this.setState({ errShow: false })
      }, 3000)
    })
  }
  valide(){
    var oFormBox = this.refs.formBox;

    return validForm(oFormBox, {
      'company':[['required'],['length:~30','字符长度过长，请小于30个字符']],
      'address': [['required'],['length:~100','字符长度过长，请小于100个字符']],
      'name': [['required'],['length:~20','字符长度过长，请小于10个字符']],
      'phone': [['required'],['phone','请输入正确的联系方式']]
    })
  }
  handleSubmit() {
    var pms = { ...this.state.formData, type: 1 };
    delete pms.read;
    // 图片单独验证
    pms.imgs = this.state.wxUploadRes.map(v=>v.serverId).join(',');

    this.valide().then(res=>{
      // 验证图片是否已经上传
      if(!pms.invitationCode) delete pms.invitationCode;
      // 必须传图
      if(!pms.imgs.length){ return Toast.info('请上传营业执照'); }
      console.info('提交结果：')
      console.log(pms)
      this.props.dispatch(requestCreateUser(pms));
    }).catch(err=>{
      if(err instanceof Error) throw err;
      err.el.focus();
      err.el.parentElement.classList.add('error');
      this.showWran(err.msg || '输入信息不正确');
    })
  }
  handleIptClick(e){
    e.target.parentElement.classList.remove('error')
  }
  uploadImgSucccess(res){
    console.log('=====')
    console.log(res)
    this.setState({ wxUploadRes: this.state.wxUploadRes.concat(res) });
  }
  uploadImgDelete(imgId){
    console.log('删除')
    console.log(imgId)
    let resData = this.state.wxUploadRes.slice();
    resData = resData.filter(v=>v.localId!==imgId);
    console.log(resData)
    this.setState({ wxUploadRes: resData });
  }
  uploadImgClick(){
    if(!(this.state.wxUploadRes.length<=4)){
      Toast.info('最多只能上传4张');
      return false;
    }
  }
  render () {
    const maxCount = 4-this.state.wxUploadRes.length;
    const regPoint = this.props.point.regPoint || 0;
    console.info(regPoint)
    console.info(maxCount)

    return (
      <div ref="formBox" className="register-frm pt20">
        <Input type="text" name="company" placeholder="请输入企业名称或都商家名称" label="企业/商家"
          onChange = { this.updateState('company') }
          onClick = { this.handleIptClick }
        ></Input>
        <Input type="text" name="address" placeholder="请输入地址" label="地址"
           onChange = { this.updateState('address') }
           onClick =  { this.handleIptClick }
        ></Input>
        <Input type="text" name="name" placeholder="请输入您的姓名" label="姓名"
           onChange={this.updateState('name')}
           onClick =  { this.handleIptClick }
        ></Input>
      <Input type="number" name="phone" placeholder="请输入您的联系方式" label="联系方式"
           onChange={this.updateState('phone')}
           onClick =  { this.handleIptClick }
          ></Input>
        <Input type="text" name="invitationCode" placeholder={`请输入邀请码，可获得${regPoint}积分`} label="邀请码"
          value={this.state.formData.invitationCode}
          readOnly={this.state.inCodeReadonly}
          onChange={this.updateState('invitationCode')}
          onClick =  { this.handleIptClick }
          ></Input>
        <Uploader name="imgs"
          maxCount = { maxCount }
          onUploadClick={this.uploadImgClick}
          onSuccessed={this.uploadImgSucccess}
          files={this.state.wxUploadRes.map(v=>v.localId)}
          onDelete={this.uploadImgDelete}
          ></Uploader>
        <div className="f28 mt30 ml30">
          <label htmlFor="agree">
            <Checkbox name="agree" name="read" onChange={this.updateState('read')} value="1" id="agree"></Checkbox>
            <span className="c-8" htmlFor="agree">我已阅读并同意</span>
          </label>
          <a href="javascript:;">《使用条款和隐私政策》</a>
        </div>
        <div className="p20 mt20">
          <Button
            onClick={this.handleSubmit.bind(this)}
            disabled={this.state.disabled}
          >进入</Button>
        </div>
        <Toptip show={this.state.errShow} type="warn">{this.state.errMsg}</Toptip>
    </div>
    )
  }
}
